<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/12/28
 * Time: 11:20
 */

namespace app\admin\controller;

use think\Db;
use \app\admin\model\Product as ProductModel;

class Purchase extends Main
{

    public $rate = [];

    /**
     * 采购列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if (checkEntranceList()) {//总公司管理员，跳转选子公司页面
            action('admin/globalFun/choose', ['backtrack' => "index"]);
            return $this->fetch(APP_PATH . request()->module() . '/view/public/choose.html');
        }
        $company_id = iget('company_id') ? iget('company_id') : isession('company_id');
        $where['company_id'] = $company_id;
        if (!checkAdministrator()) {
            $where ['user_id'] = isession('user_id');
        }
        get('order_no') && $where['order_no'] = ['like', '%' . get('order_no') . '%'];
        $data = DB::name('purchase')
            ->where($where)
            ->order("overdue asc,timestamp desc")
            ->paginate(12, false, ['query' =>
                [
                    'order_no' => get('order_no'),
                    'company_id' => iget('company_id')
                ]]);
        $list = $data->all();
        if (checkArr($list)) {
            //取出所有平台种类
            $platform = array_unique(array_column($list, 'platform'));
            foreach ($platform as $value) {
                switch ($value) {
                    case 1:
                        $store['amazon'] = $this->getAmazonStore($company_id);
                        break;//亚马逊店铺
                    case 2:
                        $store['ebay'] = $this->getEbayStore();
                        break;//ebay店铺
                    case 3:
                        $store['aliExpress'] = $this->getAliExpressStore();
                        break;//速卖通店铺
                    case 4:
                        $store['wish'] = $this->getEishStore();
                        break;//wish店铺
                }
            }

            foreach ($list as $key => $value) {
                $list[$key]['imgpath'] = $value['url'];
                switch ($value['platform']) {
                    case 1:
                        $list[$key]['url'] = isset($store['amazon'][$value['shop_id']]) ? $store['amazon'][$value['shop_id']]['org'] . "/dp/" . $value['asin'] : '';
                        break;//亚马逊店铺
                    case 2:
                        $list[$key]['url'] = '';
                        break;//ebay店铺
                    case 3:
                        $list[$key]['url'] = '';
                        break;//速卖通店铺
                    case 4:
                        $list[$key]['url'] = '';
                        break;//wish店铺
                    default :
                        $list[$key]['url'] = '';
                        break;
                }
            }
        }
        $this->assign('data', $data);
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 查看采购详情信息
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info($id)
    {
        //找货单信息
        $info = Db::name('purchase')->where('id', $id)->find();
        $info['imgpath'] = $info['url'];
        //获取采购支付账号
        $account = '';
        if ($info['account_id'] > 0) {
            $res = Db::name('pay_account')->where('id', $info['account_id'])->find();
            checkArr($res) && $account = $res['type'] . "--" . $res['account'];
        }

        //获取产品地址
        switch ($info['platform']) {
            case 1://亚马逊
                $info['url'] = $this->makeAmazonUrl($info['shop_id'], $info['asin']);
                break;
            case 2://ebay
                $info['url'] = '';
                break;
            case 3://速卖通
                $info['url'] = '';
                break;
            case 4://wish
                $info['url'] = '';
                break;
        }
        $this->assign('info', $info);
        $this->assign('account', $account);
        return $this->fetch('info');
    }

    /**
     * 修改采购信息
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit($id)
    {
        if (post()) {
            if (checkSubmitEdit()) {
                $this->error("当前状态不允许编辑信息");
            }
            $data = post();
            $data['discounts'] = $data['discounts'] ? $data['discounts'] : 0;
            $data['fee'] = $data['fee'] ? $data['fee'] : 0;

            $cost = $data['total'] + $data['fee'] - $data['discounts'];
            //不是人民币，需要换算单位
            if ($data['unit'] != 'CNY') {
                $cost = $this->toCny($cost, $data['unit']);
            }

            //更新订单信息
            $this->updateOrder($data, $cost);
            $updateData['unit_id'] = $data['unit_id'];
            $updateData['unit'] = $data['unit'];
            $updateData['cost'] = $cost;
            $updateData['total'] = $data['total'];
            $updateData['fee'] = $data['fee'];
            $updateData['discounts'] = $data['discounts'];
            $updateData['order_no'] = $data['order_no'];
            $updateData['logistics'] = $data['logistics'];
            isset($data['overdue']) && $updateData['overdue'] = $data['overdue'];
            $updateData['account_id'] = $data['account_id'];
            $updateData['voucher'] = $data['voucher'];
            $updateData['explain'] = $data['explain'];
            if (isset($data['overdue'])) {
                switch ($data['overdue']) {
                    case 3:
                        $updateData['finish_time'] = time();
                        break;
                    case 2:
                        $updateData['purchase_time'] = time();
                        break;
                    default:
                        break;
                }
            }
            Db::name('purchase')->where('id', $data['id'])->update($updateData);
            if (isset($data['overdue']) && $data['overdue'] == 3) {
                //添加钱包审核记录
                $this->rechargeLog($data, $cost);
            }
            $this->success('更新成功');
        } else {
//            $company_id = iget('company_id') ? iget('company_id') : isession('company_id');
            //找货单信息
            $find_good = Db::name('purchase')->where('id', $id)->find();
            $find_good['imgpath'] = $find_good['url'];
            //获取采购员下的支付账号
            $account = $this->getAccount(isession('user_id'));
            //获取产品地址
            switch ($find_good['platform']) {
                case 1://亚马逊
                    $find_good['url'] = $this->makeAmazonUrl($find_good['shop_id'], $find_good['asin']);
                    break;
                case 2://ebay
                    $find_good['url'] = '';
                    break;
                case 3://速卖通
                    $find_good['url'] = '';
                    break;
                case 4://wish
                    $find_good['url'] = '';
                    break;
            }
            $this->assign('find_good', $find_good);
            $this->assign('account', $account);
            $this->assign('unit', $this->getDictionary('unit'));
            return $this->fetch('edit');
        }
    }

    /**
     * 修改订单状态信息
     * @param array $data
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateOrder($data = [], $cost = 0)
    {
        switch ($data['platform']) {
            case 1://亚马逊
                $this->updateAmazonOrder($data, $cost);
                break;
            case 2://ebay
                $this->updateEbayOrder($data);
                break;
            case 3://速卖通
                $this->updateAliExpressOrder($data);
                break;
            case 4://wish
                $this->updateWishOrder($data);
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * 修改亚马逊订单
     * @param array $data
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateAmazonOrder($data = [], $cost = 0)
    {
        if (!isset($data['overdue'])) {
            return false;
        }
        if ($cost == 0) {
            return false;
        }
        $where['order_id'] = $data['order_id'];
        $where['asin'] = $data['asin'];
        $where['find_goods_id'] = $data['id'];
        switch ($data['overdue']) {
            case 3:
                $good_status = 7;
                break;
            case 2:
                $good_status = 6;
                break;
            default:
                $good_status = 5;
                break;
        }
        $price = $data['total'] + $data['fee'] - $data['discounts'];
        $updateDate = array(
            'price' => $price,
            'coin' => $data['unit'],
            'good_status' => $good_status,
            'goods_money' => $price * $data['num'],
            'cost_price' => $cost
        );
        Db::name('amazon_order_goods')->where($where)->update($updateDate);
        Db::name('amazon_order')->where('id', $data['order_id'])->update(['shipping_status' => 2]);
        return true;
    }

    /**
     * 记录钱包日志
     * @param array $data
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function rechargeLog($data = [], $cost = 0)
    {
        $company_id = isession('company_id');
        //检测充值公司钱包是否存在
        $where['company_id'] = $company_id;
        $where['purpose'] = 1;
        $wallet = DB::name('wallet')->where($where)->find();
        if (!checkArr($wallet)) {//不存在钱包，创建空钱包
            $insertData['money'] = 0;
            $insertData['company_id'] = $company_id;
            $insertData['type'] = isession('type');
            $insertData['purpose'] = 1;
            $insertData['timestamp'] = time();
            DB::name('wallet')->insert($insertData);
            $wallet_id = Db::name('wallet')->getLastInsID();
        } else {
            $wallet_id = $wallet['id'];
        }


        $log['money'] = $cost;
        $log['remark'] = $data['explain'];

        $where1['detail_id'] = $data['id'];
        $where1['project'] = 3;
        $where1['purpose'] = 1;
        $where1['operate'] = 2;
        $where1['audit'] = 1;
        $wallet_log = DB::name('wallet_log')->where($where1)->find();
        if (checkArr($wallet_log)) {//存在记录，更新
            DB::name('wallet_log')->where('id', $wallet_log['id'])->update($log);
            return true;
        }

        $log['wallet_id'] = $wallet_id;
        $log['company_id'] = $company_id;
        $log['type'] = isession('type');
        $log['purpose'] = 1;
        $log['operate'] = 2;
        $log['operate_company_id'] = $company_id;
        $log['operate_date'] = time();
        $log['reason_id'] = '';
        $log['reason'] = '采购商品';
        $log['resource_id'] = '';
        $log['project'] = 3;
        $log['detail_id'] = $data['id'];
        $log['audit'] = 1;
        $log['operate_audit'] = isession('type');
        $log['operate_uid'] = isession('user_id');
        $log['operate_name'] = ssession('username');
        $log['operate_truename'] = ssession('truename');
        $log['timestamp'] = time();
        DB::name('wallet_log')->insert($log);
    }

    /**
     * 外汇换算人民币
     * @param int $money
     * @param string $unit
     * @return float|int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function toCny($money = 0, $unit = '')
    {
        if ($money == 0 || $unit == '') {
            return 0;
        }
        $rate = $this->getCNY($unit, $type = 'update');
        return $money / $rate;
    }
}